﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;

namespace NETXPF.WPF
{
    public class DropDownButton : ButtonBase
    {
        // *** Dependency Properties ***

        public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(DropDownButton), new FrameworkPropertyMetadata(IsCheckedPropertyChangedCallback));
        public static readonly DependencyProperty DropDownProperty = DependencyProperty.Register("DropDown", typeof(ContextMenu), typeof(DropDownButton), new FrameworkPropertyMetadata(DropDownPropertyChangedCallback));

        // *** Constructors ***

        public DropDownButton()
        {
            this.Click += new RoutedEventHandler(DropDownButton_Click);
        }

        void DropDownButton_Click(object sender, RoutedEventArgs e)
        {
            IsChecked = !IsChecked;
            if (DropDown != null)
                DropDown.IsOpen = IsChecked;
        }

        // *** Properties ***

        public ContextMenu DropDown
        {
            get
            {
                return (ContextMenu)GetValue(DropDownProperty);
            }
            set
            {
                SetValue(DropDownProperty, value);
            }
        }

        public bool IsChecked
        {
            get
            {
                return (bool)GetValue(IsCheckedProperty);
            }
            set
            {
                SetValue(IsCheckedProperty, value);
            }
        }

        static void DropDownPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DropDownButton)d).DropDownPropertyChangedCallback(e);
        }
        static void IsCheckedPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DropDownButton)d).IsCheckedPropertyChangedCallback(e);
        }
        void IsCheckedPropertyChangedCallback(DependencyPropertyChangedEventArgs e)
        {
        }

        void DropDownPropertyChangedCallback(DependencyPropertyChangedEventArgs e)
        {
            if (DropDown != null)
            {
                DropDown.PlacementTarget = this;
                DropDown.Placement = PlacementMode.Bottom;
                DropDown.Closed += new RoutedEventHandler(DropDown_Closed);
            }
        }

        void DropDown_Closed(object sender, RoutedEventArgs e)
        {
            IsChecked = false;
        }
    }
}
